package com.kuaiyin.controller.upload;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.kuaiyin.exception.BaseException;
import com.kuaiyin.result.Result;
import com.kuaiyin.utils.AliOSSProperties;
import com.kuaiyin.utils.AliyunOSSUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;


@Slf4j
@Tag(name = "文件上传")
@RestController
public class UploadController {

    @Autowired
    private AliOSSProperties aliOSSProperties;


    @Operation(summary = "文件上传存oss")
    @PostMapping("/upload")
    public Result<Map<String, String>> upload(MultipartFile file) {
        try {
            // 1. 校验文件是否为空
            if (file.isEmpty()) {
                throw BaseException.of(1001, "文件上传为空");
            }
            // 2. 校验文件大小（例如限制为 10MB）
            long maxSize = 10 * 1024 * 1024; // 10MB
            if (file.getSize() > maxSize) {
                throw BaseException.of(1002, "文件超过最大限制");
            }
            // 3. 获取文件后缀
            String originalFilename = file.getOriginalFilename();
            String extName = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 4. 使用 byte[] 上传（当前方式）
            String url = AliyunOSSUtils.upload(
                    aliOSSProperties.getEndpoint(),
                    aliOSSProperties.getBucketName(),
                    file.getBytes(), // ⚠️ 注意：大文件会导致 OOM
                    extName
            );
            return Result.success(Collections.singletonMap("url", url));
        } catch (IOException e) {
            throw BaseException.of(1003, "文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Operation(summary = "文件上传获取内容")
    @PostMapping("/upload/getContent")
    public String uploadGetContent(MultipartFile file) {
        try {
            //1、判断是否是jmx文件
            String originalFilename = file.getOriginalFilename();
            if (StrUtil.isBlank(originalFilename) || !StrUtil.endWithIgnoreCase(originalFilename, ".jmx")) {
                throw BaseException.of(1004, "请上传jmx文件");
            }
            // 2. 用 Hutool 读取文件内容为字符串（默认UTF-8）
            return IoUtil.readUtf8(file.getInputStream());

        } catch (Exception e) {
            throw BaseException.of(0, String.valueOf(e));
        }
    }
}
